package cn.tinkling;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public final class HanziToPinyin {

	private final HanyuPinyinOutputFormat mOutputFormat;

	public HanziToPinyin() {
		mOutputFormat = new HanyuPinyinOutputFormat();
		mOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		mOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		mOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
	}

	public String getPinyin(String src) {
		char[] chars = src.toCharArray();

		StringBuilder sb = new StringBuilder();
		String[] temp;
		int count = 0;
		boolean hasLetter = false;
		HanyuPinyinOutputFormat outputFormat = mOutputFormat;
		try {
			for (char c : chars) {
				if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
					sb.append(c);
					hasLetter = true;
					continue;
				}

				if (hasLetter) {
					count++;
					hasLetter = false;
					sb.append('_');
				}

				temp = PinyinHelper.toHanyuPinyinStringArray(c, outputFormat);
				if (temp != null) {
					if (count < 5) {
						sb.append(temp[0]);
						sb.append('_');
					} else {
						sb.append(temp[0].charAt(0));
					}

					count++;
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
			return e.getMessage();
		}

		if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '_') {
			sb.deleteCharAt(sb.length() - 1);
		}

		return sb.toString();
	}

}
